const colorPicker = document.querySelector('#color')
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')

function init() {
  const width = 500
  const height = 300
  canvas.width = width * devicePixelRatio
  canvas.height = height * devicePixelRatio
  canvas.style.width = `${width}px`
  canvas.style.height = `${height}px`
}

init()

class Rectangle {
  constructor(color, startX, startY) {
    this.color = color
    this.startX = startX
    this.startY = startY
    this.endX = startX
    this.endY = startY
  }

  get minX() {
    return Math.min(this.startX, this.endX)
  }
  get minY() {
    return Math.min(this.startY, this.endY)
  }
  get maxX() {
    return Math.max(this.startX, this.endX)
  }
  get maxY() {
    return Math.max(this.startY, this.endY)
  }

  draw() {
    ctx.beginPath()
    ctx.moveTo(this.minX * devicePixelRatio, this.minY * devicePixelRatio)
    ctx.lineTo(this.minX * devicePixelRatio, this.maxY * devicePixelRatio)
    ctx.lineTo(this.maxX * devicePixelRatio, this.maxY * devicePixelRatio)
    ctx.lineTo(this.maxX * devicePixelRatio, this.minY * devicePixelRatio)
    ctx.closePath()
    ctx.fillStyle = this.color
    ctx.fill()
    ctx.strokeStyle = '#fff'
    ctx.lineCap = 'square'
    ctx.lineWidth = 3 * devicePixelRatio
    ctx.stroke()
  }

  isInside(x, y) {
    return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY
  }
}

const shapes = []

function draw() {
  requestAnimationFrame(draw)
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  shapes.forEach(shape => shape.draw())
}

draw()

function getShapeAtPoint(x, y) {
  for (let i = shapes.length - 1; i >= 0; i--) {
    const shape = shapes[i]
    if (shape.isInside(x, y)) {
      return shape
    }
  }
  return null
}

canvas.onmousedown = (e) => {
  const rect = canvas.getBoundingClientRect()
  const clickX = e.clientX - rect.left
  const clickY = e.clientY - rect.top
  let shape = getShapeAtPoint(clickX, clickY)
  if (shape) {
    // 拖动
    const { startX, startY, endX, endY } = shape

    window.onmousemove = (e) => {
      const disX = e.clientX - rect.left - clickX
      const disY = e.clientY - rect.top - clickY
      shape.startX = startX + disX
      shape.startY = startY + disY
      shape.endX = endX + disX
      shape.endY = endY + disY
    }
  } else {
    // 创建新的矩形
    shape = new Rectangle(colorPicker.value, clickX, clickY)
    shapes.push(shape)

    window.onmousemove = (e) => {
      shape.endX = e.clientX - rect.left
      shape.endY = e.clientY - rect.top
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      shapes.forEach(shape => shape.draw())
    }
  }

  window.onmouseup = () => {
    window.onmousemove = null
    window.onmouseup = null
  }
}